package com.qdxwx.web.controller.ajax;

import com.qdxwx.captcha.Constants;
import com.qdxwx.common.cache.CacheUtils;
import com.qdxwx.common.constants.CacheConstants;
import com.qdxwx.common.json.AjaxResult;
import com.qdxwx.common.utils.TKString;
import com.qdxwx.data.service.user.UserService;
import com.qdxwx.sms.QdxSmsClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import jakarta.servlet.http.HttpServletRequest;

/**
 * @author ZhiYong
 * @createTime 2020/9/10
 * @description
 */
@Controller
@RequestMapping("/ajax")
public class AjaxSendCodeController {
    @Autowired
    private UserService userService;

    //发送手机验证码
    @RequestMapping("/sendCode.json")
    @ResponseBody
    public AjaxResult sendLoginCode(HttpServletRequest request) {
        String type = request.getParameter("type");
        String mobile = request.getParameter("mobile");
        String ranCode = request.getParameter("ranCode");
        if (TKString.isEmpty(mobile)) {
            return AjaxResult.error("手机号码不能为空！");
        }
        if (!TKString.isMobile(mobile)) {
            return AjaxResult.error("手机号码格式错误！");
        }
        //获取Session中验证码
        String sessionCode = (String) request.getSession().getAttribute(Constants.CAPTCHA_SESSION_KEY);
        if (sessionCode == null || !sessionCode.equals(ranCode)) {
            return AjaxResult.error("验证码不正确！");
        }
        request.getSession().removeAttribute(Constants.CAPTCHA_SESSION_KEY);

        String mobileCode = (String) CacheUtils.get(CacheConstants.MOBILE_SMS_PRE + mobile);
        if (!TKString.isEmpty(mobileCode)) {
            return AjaxResult.error("登录码已经发送，如未收到，请5分钟后再次尝试！");
        }
        mobileCode = TKString.getRanNumber(6);
        //把验证码放入缓存
        CacheUtils.set(CacheConstants.MOBILE_SMS_PRE + mobile, mobileCode, 300);
        //Map<String, Object> tenConfig = websiteProfileService.getMap(WebsiteProfileType.tencentCloud);
        if (request.getServerName().equals("localhost")) {
            System.out.println("手机码:" + mobileCode);
            return AjaxResult.success("短信码已输出在控制台");
        }
        QdxSmsClient clientQdx = new QdxSmsClient();
        boolean sendState;
        if (type.equals("register")) {
            sendState = clientQdx.sendRegisterCode(mobile, mobileCode);
        } else if (type.equals("login")) {
            if (!userService.isExistMobile(mobile)) {
                return AjaxResult.error("该手机号未注册！");
            }
            sendState = clientQdx.sendLoginCode(mobile, mobileCode);
        } else {
            sendState = clientQdx.sendOtherCode(mobile, mobileCode);
        }
        if (sendState) {
            return AjaxResult.success("短信发送成功，请查收");
        } else {
            return AjaxResult.error("短信发送失败，请重试");
        }
    }
}
